# ========================================================================= #
# Project: Lexical Ambiguity in Political Rhetoric (BJPolS)
# - Script: Replicate embedding results using conText package
# - Author: Patrick Kraft (patrickwilli.kraft@uc3m.es)
# ========================================================================= #


# Load packages and custom functions --------------------------------------

source(here::here("code/00-func.R"))


# Load dictionaries & speeches --------------------------------------------

load(here("out/speeches.Rdata"))
glove <- readRDS(here("in/glove.rds"))
khodakA <- readRDS(here("in/khodakA.rds"))
mfd <- dictionary(file=here("in/mfd2.0.dic"), format="LIWC")
mfd_list <- list(
  `_care_` = c(mfd$care.vice, mfd$care.virtue),
  `_fairness_` = c(mfd$fairness.vice, mfd$fairness.virtue),
  `_loyalty_` = c(mfd$loyalty.vice, mfd$loyalty.virtue),
  `_authority_` = c(mfd$authority.vice, mfd$authority.virtue),
  `_sanctity_` = c(mfd$sanctity.vice, mfd$sanctity.virtue)
)


# Run conText embedding regressions ---------------------------------------

x <- list(sotu, qs, co, pl, deb, email)
y <- c("a) US State of the Union",
       "b) UK Queen's Speeches",
       "c) US Convention Speeches",
       "d) UK Party Leader Speeches",
       "e) US Presidential Debates",
       "f) US Senate Emails")

plot_df <- bind_rows(
  map2_dfr(x, y, ~embedReg(.x, "_care_", type = .y, seed = 42)),
  map2_dfr(x, y, ~embedReg(.x, "_fairness_", type = .y, seed = 42)),
  map2_dfr(x, y, ~embedReg(.x, "_loyalty_", type = .y, seed = 42)),
  map2_dfr(x, y, ~embedReg(.x, "_authority_", type = .y, seed = 42)),
  map2_dfr(x, y, ~embedReg(.x, "_sanctity_", type = .y, seed = 42)),
)


# Plot results ------------------------------------------------------------

plot_df %>%
  filter(coefficient != "party_Liberal") %>% 
  mutate(
    foundation = recode_factor(foundation, 
                               `_sanctity_` = "Sanctity",
                               `_authority_` = "Authority",
                               `_loyalty_` = "Loyalty", 
                               `_fairness_` = "Fairness", 
                               `_care_` = "Care")) %>% 
  ggplot(aes(x = foundation, y = normed.estimate, 
             ymin = normed.estimate - qnorm(.975) * std.error, 
             ymax = normed.estimate + qnorm(.975) * std.error)) +
  geom_hline(yintercept = 0, col = "darkgrey") +
  geom_point(size = 1.5) +
  geom_errorbar(width=0) +
  geom_errorbar(aes(ymin = normed.estimate - qnorm(.95) * std.error, 
                    ymax = normed.estimate + qnorm(.95) * std.error), width=.2) +
  facet_wrap(.~type, dir = "v", ncol = 3) +
  labs(y = "Normed conText coefficients", 
       x = NULL) +
  coord_flip() +
  theme_mft()
ggsave(here("out/appD1-conText.png"), height = 3.5, width = 6, dpi = 600)
